﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Xml.Linq; 

namespace CommonUtils
{
    public static class BitLyAPI
    {
        /// <summary>     
        /// Shorten the URL in parameter using the bit.ly API
        /// </summary>
        public static BitlyResults ShortenUrl(string longUrl)
        {
            try {
                String sURL = string.Format("http://api.bit.ly/shorten?format=xml&version=2.0.1&longUrl={0}&login={1}&apiKey={2}",
                HttpUtility.UrlEncode(longUrl), CommonUtilsSettings.Default.BitLyApiUser, CommonUtilsSettings.Default.BitLyApiKey);
                XDocument resultXml = XDocument.Load(sURL);
                IEnumerable<BitlyResults> ienResults = (from result in resultXml.Descendants("nodeKeyVal")
                         select new BitlyResults
                         {
                             UserHash = result.Element("userHash").Value,
                             ShortUrl = result.Element("shortUrl").Value
                         });
                return ienResults.Single();
            }
            catch (Exception e)
            {
                System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame();
                LogWriter.AddLog(e, LogStatus.Error, CommonUtilsSettings.Default.ApplicationName, sf.GetMethod().Name);
                throw new Exception(sf.GetMethod().Name + " unexpected error", e);
            }
        }

    }

    public class BitlyResults
    {
        public string UserHash { get; set; }
        public string ShortUrl { get; set; }
    }
}
